<template>
  <el-row :gutter="10" class="mt5 mb8" style="padding-left: 5px">
    <el-col v-if="!isQuoted" :span="1.5">
      <el-button plain type="primary" @click="handleAdd">
        <template #icon>
          <i-ep-plus/>
        </template>
        添加项目
      </el-button>
    </el-col>
    <el-col v-if="isQuoted" :span="1.5">
      <el-button color="#8888ff" plain style="float: right;margin-right: 8px;"
                 @click="templateOpenOk">
        <svg-icon class="mr5" icon-class="template"/>
        引用
      </el-button>
    </el-col>
    <el-col :span="1.5">
      <el-button type="primary" @click="getList">
        <template #icon>
          <i-ep-search/>
        </template>
        刷新
      </el-button>
    </el-col>
  </el-row>
  <el-table
    :border="true" :data="outpTreatRecTemplateList" :header-cell-style="$headerCellStyle" :stripe="true" height="665px"
    highlight-current-row @selection-change="handleSelectionChange"
  >
    <el-table-column v-if="isQuoted" :align="'center'" type="selection" width="40"/>
    <el-table-column v-if="isQuoted" :align="'center'" label="模板主题名称" min-width="90" prop="title">
      <template #default="scope">
        <span class="ys-css">{{ scope.row.title }}</span>
      </template>
    </el-table-column>
    <el-table-column
      :align="'center'"
      :show-overflow-tooltip="true"
      label="类别"
      prop="itemClass"
      width="80"
    >
      <template #default="scope">
        <dict-data-tag
          :options="dictDataMap['bill_item_class_dict']"
          :value="scope.row.itemClass"
        />
      </template>
    </el-table-column>
    <el-table-column
      :align="'center'"
      :show-overflow-tooltip="true"
      label="项目名称"
      prop="itemName"
    />
    <el-table-column
      :align="'center'"
      :show-overflow-tooltip="true"
      label="频次"
      prop="performFreqName"
      width="120"
    />
    <el-table-column
      :align="'center'"
      :show-overflow-tooltip="true"
      label="天数"
      prop="abidance"
      width="50"
    />
    <el-table-column
      :align="'center'"
      :show-overflow-tooltip="true"
      label="规格"
      prop="packageSpec"
      width="80"
    />
    <el-table-column
      :align="'center'"
      :show-overflow-tooltip="true"
      label="单价(元)"
      prop="price"
      width="100"
    >
      <template #default="scope">
        {{ parseFloat(scope.row.price).toFixed(2) }}
      </template>
    </el-table-column>
    <el-table-column
      :align="'center'"
      :show-overflow-tooltip="true"
      label="数量"
      prop="num"
      width="80"
    />
    <el-table-column
      :align="'center'"
      :show-overflow-tooltip="true"
      label="总价格(元)"
      prop="sumPrice"
      width="100"
    >
      <template #default="scope">
        {{ parseFloat(scope.row.sumPrice).toFixed(2) }}
      </template>
    </el-table-column>
    <el-table-column v-if="isQuoted" :align="'center'" label="执行科室" prop="implementDept" width="150">
      <template #default="scope">
        <dept-list
          v-model="scope.row.implementDept"
          :dept-id="scope.row.implementDept"
          :org-id="props.orgId"
          :placeholder="'请选择执行科室'"
          style="width: 100%"
          @deptChange="deptChange($event,scope.row)"
        />
      </template>
    </el-table-column>
    <el-table-column
      :align="'center'"
      label="诊断"
      width="180">
      <template #default="scope">
        <diagnosis-select v-model="scope.row.icdCode" @option-change="optionChange($event, scope.$index,scope.row)"/>
      </template>
    </el-table-column>
    <el-table-column
      :align="'center'"
      :show-overflow-tooltip="true"
      label="备注信息"
      prop="remarks"
      width="120"
    />
    <el-table-column
      v-if="!isQuoted" :align="'left'" class-name="small-padding fixed-width"
      label="操作"
      width="100"
    >
      <template #default="scope">
        <el-tooltip class="item" content="修改" effect="dark" placement="top">
          <el-button circle type="success" @click="handleUpdate(scope.row)">
            <template #icon>
              <i-ep-edit/>
            </template>
          </el-button>
        </el-tooltip>
        <el-tooltip
          class="item"
          content="删除"
          effect="dark"
          placement="top"
        >
          <el-button circle type="danger" @click="handleDelete(scope.row)">
            <template #icon>
              <i-ep-delete/>
            </template>
          </el-button>
        </el-tooltip>
      </template>
    </el-table-column>
  </el-table>

  <!-- 添加或修改处置治疗对话框 -->
  <el-dialog
    v-model="open"
    :close-on-click-modal="false"
    append-to-body
    title="开治疗"
    width="500px"
    @close="cancel"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-table-column v-if="isQuoted" :align="'center'" label="模板主题名称" min-width="150" prop="title">
        <template #default="scope">
          <span class="ys-css">{{ scope.row.title }}</span>
        </template>
      </el-table-column>
      <el-form-item label="项目名称" prop="itemName">
        <el-input v-if="isShow" v-model="form.itemName"
                  @focus="isShowItemNameFocus()">
        </el-input>
        <automatic-completion
          v-else ref="itemAutomatic"
          v-model="form.itemName" :dict-array="dictArray"
          :table-body-list="tableBodyList"
          :table-head-list="tableHeadList"
          :title="itemTitle"
          style="width: 100%"
          @itemNameInput="itemNameInput"
          @row-click="rowClick"
        />
      </el-form-item>
      <el-form-item label="数量" prop="num">
        <el-input v-model="form.num" placeholder="请输入数量" @blur="numInput"/>
      </el-form-item>
      <el-form-item label="天数" prop="abidance">
        <el-input v-model="form.abidance" placeholder="请输入天数"/>
      </el-form-item>
      <el-form-item label="频次" prop="performFreq">
        <perform-index
          ref="performIndex"
          :placeholder="'请选择频次'"
          :value="form.performFreq"
          style="width: 100%"
          @performFreqInfoChange="performFreqInfoChange"
        />
      </el-form-item>
      <el-form-item label="单价" prop="price">
        <el-input v-model="form.price" disabled placeholder="请输入单价">
          <template #append>元</template>
        </el-input>
      </el-form-item>
      <el-form-item label="总价格" prop="sumPrice">
        <el-input v-model="form.sumPrice" disabled placeholder="请输入总价格">
          <template #append>元</template>
        </el-input>
      </el-form-item>
      <el-table-column v-if="isQuoted" :align="'center'" label="执行科室" prop="implementDept" width="150">
        <template #default="scope">
          <dept-list
            v-model="scope.row.implementDept"
            :dept-attribute-str="'5'"
            :dept-id="scope.row.implementDept"
            :org-id="props.orgId"
            :placeholder="'请选择执行科室'"
            style="width: 100%"
            @deptChange="deptChange($event,scope.row)"
          />
        </template>
      </el-table-column>
      <el-form-item label="备注信息" prop="remarks">
        <el-input v-model="form.remarks" placeholder="请输入备注信息"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>

import {useDictStoreHook} from "@/store/modules/dict.ts";
import {
  delTemplateDetail,
  getTemplateDetail,
  insertBoByWholeSet,
  listTemplateDetail,
  updateTemplateDetail
} from "@/api/patient/templateDetail.ts";
import {templateSubmitOk} from "@/api/clinicOrder/outpTreatRec"
import {clinicTableHeadList, jsonStrInObj} from "@/utils/autoComplete.ts";
import {autoBuildQuery} from "@/api/base/clinicItemDict.ts";
import {useUserStoreHook} from "@/store/modules/user.ts";

const dictStore = useDictStoreHook();

let dictDataMap = ref(
  dictStore.isTypeGetData(
    "clinic_or_visit",
    "charge_flag_dict",
    "bill_item_class_dict",
    "sys_yes_no"
  )
);
const {proxy} = getCurrentInstance() as any;

const props = defineProps({
  templateMasterId: {
    type: String,
    default: ""
  },
  orgId: {
    type: String,
    default: ""
  },
  // 是否从引用加载
  isQuoted: {
    type: Boolean,
    default: false
  }
})

const emits = defineEmits(['historyCancel']);
const rules = ref<any>({})
const formRef = ref()
const open = ref(false)
// 项目选择自动补全窗体名称
const itemTitle = ref("选择项目");
// 项目选择自动补全表格表头
const tableHeadList = ref(jsonStrInObj(clinicTableHeadList));
// 项目选择自动补全表格数据
const tableBodyList = ref([]);
// 项目选择自动补全字典数组
const dictArray = ref(["bill_item_class_dict"]);

const itemAutomatic = ref();

const useUserStore = useUserStoreHook();
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo

const selectionAny = ref<any>([]);
const ids = ref<any>([]);

const form = ref<any>({
  type: '5',
  templateMasterId: props.templateMasterId,
  orgId: props.orgId,
});
const autoForm = ref<any>({
  clinicItemName: "",
  itemInfo: "",
  orgId: props.orgId,
  isFiltrationContrastExist: true,
  notInSelect: [],
});
const queryParams = ref<any>({
  type: '5',
  orgId: props.orgId,
  templateMasterId: props.templateMasterId,
});

const outpTreatRecTemplateList = ref<any>([])

/** 项目列表行点击事件 */
function rowClick(row: any) {
  itemAutomatic.value.closePopover();
  isShow.value = true
  form.value.clinicItemId = row.clinicItemId;
  form.value.itemName = row.itemName;
  form.value.inputCode = row.inputCode;
  form.value.itemClass = row.itemClass;
  form.value.packageSpec = row.itemSpec;
  autoForm.value.clinicItemName = row.itemName;
  const subTotal = row.subTotal ? row.subTotal : 0;
  form.value.price = subTotal.toFixed(2);
  form.value.sumPrice = (subTotal * form.value.num).toFixed(2);
  tableBodyList.value = [];
}


/**
 * 自动补全上边input获得焦点事件
 * @param _index
 * @param row
 */
let isShow = ref(true);

function isShowItemNameFocus() {
  isShow.value = false
  nextTick(() => {
    itemAutomatic.value.init()
    itemAutomatic.value.setItemName(form.value.itemName)
    itemAutomatic.value.focusInput()
  })
}


/** 项目名称自动补全检索 */
function itemNameInput(itemName: String) {
  autoForm.value.itemInfo = itemName;
  getListClinicItemDict();
}

/** 自动补全后台查询 */
function getListClinicItemDict() {
  if (autoForm.value.itemInfo) {
    // form.value.notInSelect = ['A', 'B', 'F', 'C', 'D', 'E', 'F', 'G', 'H']
    autoForm.value.notInSelect = ["A", "B"];
    autoForm.value.orgId = props.orgId;
    // 是否过滤已存在的项目标记
    autoForm.value.isFiltrationContrastExist = true;
    autoBuildQuery(autoForm.value).then((res) => {
      tableBodyList.value = res.data;
      // 打开自动补全弹出框
      itemAutomatic.value.init();
    });
  } else {
    tableBodyList.value = [];
  }
}

/** 默认频次选择事件 */
function performFreqInfoChange(obj: any) {
  form.value.performFreq = obj.freqId;
}

/** 数量改变事件 */
function numInput() {
  form.value.sumPrice = (form.value.price * form.value.num).toFixed(2);
}


/** 提交按钮 */
function submitForm() {
  (formRef.value as any).validate((valid) => {
    if (valid) {
      if (form.value.detailId) {
        updateTemplateDetail(form.value).then(() => {
          reset()
          ElMessage.success("修改成功");
          open.value = false;
          nextTick(() => {
            itemAutomatic.value.itemNameEmpty();
          })
          getList();
        });
      } else {
        form.value.detailBoList = [{
          abidance: form.value.abidance,
          clinicItemId: form.value.clinicItemId,
          itemClass: form.value.itemClass,
          itemName: form.value.itemName,
          num: form.value.num,
          performFreq: form.value.performFreq,
          price: form.value.price,
          remarks: form.value.remarks,
          sumPrice: form.value.sumPrice,
          templateMasterId: form.value.templateMasterId,
          type: form.value.type,
          packageSpec: form.value.packageSpec
        }]
        insertBoByWholeSet(form.value)
          .then(() => {
            reset()
            nextTick(() => {
              itemAutomatic.value.itemNameEmpty();
            })
            ElMessage.success("新增成功");
            open.value = false;
            getList();
          })
      }
    }
  });
}

/** 新增按钮操作 */
function handleAdd() {
  open.value = true;
}

function cancel() {
  open.value = false;
}

function reset() {
  form.value = {
    abidance: undefined,
    clinicItemId: undefined,
    itemClass: undefined,
    itemName: undefined,
    num: undefined,
    performFreq: undefined,
    price: undefined,
    remarks: undefined,
    sumPrice: undefined,
    templateMasterId: form.value.templateMasterId,
    orgId: props.orgId,
    type: "5"
  }
}

function handleUpdate(row: any) {
  reset();
  const idThis = row.detailId
  open.value = true
  getTemplateDetail(idThis).then((res: any) => {
    form.value = res.data;
    nextTick(() => {
      itemAutomatic.value.setItemName(form.value.itemName)
    })
  })
}

function handleDelete(row: any) {
  ElMessageBox.confirm("是否确认删除？", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    delTemplateDetail(row.detailId).then(() => {
      ElMessage.success("删除成功");
      getList();
    });
  })
    .catch(() => {
    });
}

function getList() {
  listTemplateDetail(queryParams.value).then((response: any) => {
    outpTreatRecTemplateList.value = response.data;
  });
}

/**
 * 模板引用多选事件
 */
function handleSelectionChange(selection) {
  selectionAny.value = selection;
  ids.value = selection.map((item: any) => item.id);
}

/**
 * 执行科室选择
 * @param e
 * @param row
 */
function deptChange(e: any, row: any) {
  row.implementDept = e.deptId;
}


/**
 * 引用模板数据
 */
function templateOpenOk() {
  if (ids.value.length == 0) {
    return ElMessage.error("请选择一条数据");
  }
  let saveByTemplateArray: any = []
  for (let i = 0; i < selectionAny.value.length; i++) {
    const item = selectionAny.value[i];
    if (!item.implementDept) {
      return ElMessage.error("请选择执行科室");
    }
    const saveByTemplate = {
      abidance: item.abidance,
      applyDept: proxy.$currentSelectDept,
      applyUser: userInfo.userId,
      chargeFlag: "1",
      clinicId: proxy.$clinicId,
      clinicItemId: item.clinicItemId,
      confirmFlag: "N",
      implementDept: item.implementDept,
      inoroutFlag: "4",
      isApply: "N",
      isPhy: "N",
      itemClass: item.itemClass,
      itemName: item.itemName,
      itemSpec: item.packageSpec,
      num: Number(item.num),
      orgId: props.orgId,
      patientId: proxy.$patientId,
      performFreq: item.performFreq,
      price: Number(item.price),
      remarks: item.remarks,
      sumPrice: Number(item.sumPrice),
      whetherToComeInAttached: false,
      icdCode: item.icdCode,
      icdName: item.icdName,
      diagnosisList: item.diagnosisList
    }
    saveByTemplateArray.push(saveByTemplate);
  }
  ElMessageBox.confirm("是否确认使用模板？", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    const data = {
      saveByTemplateArray: saveByTemplateArray
    }
    templateSubmitOk(data).then(() => {
      emits('historyCancel')
      ElMessage.success("保存成功");
    });
  })
    .catch(() => {
    });
}

/**
 * 诊断选择事件
 * @param e
 * @param index
 * @param row
 */
function optionChange(e, index, row) {
  row.diagnosisList = e
  row.icdCode = e.icdCode
  row.icdName = e.icdName
}

defineExpose({
  getList
})
</script>


<style scoped>
.el-dialog__header.show-close {
  margin-bottom: 40px;
}
</style>
